package com.mhc.suzuki.service.impl;

import com.mhc.haval.security.model.User;
import com.mhc.suzuki.constant.ErrorCodeEnum;
import com.mhc.suzuki.constant.PaymentRequestStatusEnum;
import com.mhc.suzuki.constant.PaymentWayEnum;
import com.mhc.suzuki.dal.model.LoanInfoDO;
import com.mhc.suzuki.dal.model.OrderDO;
import com.mhc.suzuki.dal.model.PaymentRequestDO;
import com.mhc.suzuki.dal.query.PaymentRequestQuery;
import com.mhc.suzuki.exception.SuzukiCommonException;
import com.mhc.suzuki.manager.LoanInfoManager;
import com.mhc.suzuki.manager.OrderManager;
import com.mhc.suzuki.manager.PaymentRequestManager;
import com.mhc.suzuki.service.PaymentRequestService;
import com.mhc.suzuki.util.BeanCopierUtil;
import com.mhc.suzuki.vo.PaymentRequestVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class PaymentRequestServiceImpl implements PaymentRequestService {

    @Autowired
    private PaymentRequestManager paymentRequestManager;
    @Autowired
    private OrderManager orderManager;
    @Autowired
    private LoanInfoManager loanInfoManager;

    @Override
    public PaymentRequestVO getPaymentRequest(String orderNO) {
        PaymentRequestQuery paymentRequestQuery = new PaymentRequestQuery();
        paymentRequestQuery.createCriteria().andOrderNoEqualTo(orderNO);
        List<PaymentRequestDO> paymentRequestDOList = paymentRequestManager.selectByQuery(paymentRequestQuery);
        if (paymentRequestDOList != null && paymentRequestDOList.size() > 0) {
            PaymentRequestDO paymentRequestDO = paymentRequestDOList.get(0);
            PaymentRequestVO paymentRequestVO = BeanCopierUtil.convert(paymentRequestDO, PaymentRequestVO.class);
            return paymentRequestVO;
        } else {
            return null;
        }
    }

    @Override
    public List<PaymentRequestVO> getPaymentRequestList(String orderNO, Integer applyStatus) {
        PaymentRequestQuery paymentRequestQuery = new PaymentRequestQuery();
        paymentRequestQuery.createCriteria().andOrderNoEqualTo(orderNO);
        List<PaymentRequestVO> paymentRequestVOList = new ArrayList<>();
        List<PaymentRequestDO> paymentRequestDOList = paymentRequestManager.selectByQuery(paymentRequestQuery);
        if (paymentRequestDOList != null && paymentRequestDOList.size() > 0) {
            paymentRequestDOList.forEach(paymentRequestDO -> {
                PaymentRequestVO paymentRequestVO = BeanCopierUtil.convert(paymentRequestDO, PaymentRequestVO.class);
                paymentRequestVOList.add(paymentRequestVO);
            });
        }
        return paymentRequestVOList;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean addOrUpdatePaymentRequest(PaymentRequestDO paymentRequestDO) {
        PaymentRequestQuery paymentRequestQuery = new PaymentRequestQuery();
        paymentRequestQuery.createCriteria().andOrderNoEqualTo(paymentRequestDO.getOrderNo());
        int count = paymentRequestManager.countByQuery(paymentRequestQuery);
        if (count > 0) {
            paymentRequestDO.setGmtModified(LocalDateTime.now());
            int updateCount = paymentRequestManager.updateByQuerySelective(paymentRequestDO, paymentRequestQuery);
            if (updateCount > 0) {
                return Boolean.TRUE;
            } else {
                return Boolean.FALSE;
            }
        } else {
            paymentRequestManager.insertSelective(paymentRequestDO);
            return Boolean.TRUE;
        }
    }


    /**
     * 发起打款申请，新增记录到垫款申请表
     * @param orderNo
     * @param logedUser
     * @return
     * @throws SuzukiCommonException
     */
    @Override
    public Boolean savePaymentRequest(String orderNo,User logedUser) throws SuzukiCommonException {
        /**根据订单号查询当前订单下的垫款信息**/
        log.info("正在查询订单{}下的垫款信息...", orderNo);
        LoanInfoDO loanInfo = loanInfoManager.selectByOrderNo(orderNo);
        OrderDO orderList = orderManager.selectByOrderNo(orderNo);
        if(orderList!=null && loanInfo!=null){
            /**查询不为空,新增垫款申请记录**/
            log.info("开始录入...");
            PaymentRequestDO paymentRequestRecord = new PaymentRequestDO();
            paymentRequestRecord.setOrderNo(orderNo);   //订单号
            paymentRequestRecord.setCustomerId(orderList.getCustomerId());  //客户编号
            paymentRequestRecord.setLoanInfoId(loanInfo.getLoanInfoId());  //贷款信息ID
            paymentRequestRecord.setPaymentWay(PaymentWayEnum.ONLIINEBANK.getCode());  //支付方式
            paymentRequestRecord.setLoaningAmount(loanInfo.getLoanAmount()); //垫资金额
            paymentRequestRecord.setPayeeAccountName(loanInfo.getPayeeDealerName());  //收款方账号名称
            paymentRequestRecord.setPayeeBankName(loanInfo.getPayeeBankName());  //收款方开户银行名称
            paymentRequestRecord.setPayeeBankCard(loanInfo.getPayeeBankCard());  //收款方银行卡号
            paymentRequestRecord.setStaffId(logedUser.getStaffId());   //业务员ID
            paymentRequestRecord.setStaffName(logedUser.getStaffName()); //业务员名称
            paymentRequestRecord.setDeptId(logedUser.getDeptId());    //业务员所属部门ID
            paymentRequestRecord.setDeptName(logedUser.getDeptName());  //业务员所属部门名称
            paymentRequestRecord.setApplyStatus(PaymentRequestStatusEnum.NOTPAID.getCode());  //申请状态
            log.info("录入完成...");
            PaymentRequestQuery paymentRequestQuery = new PaymentRequestQuery();
            paymentRequestQuery.createCriteria().andOrderNoEqualTo(orderNo);
            List<PaymentRequestDO> paymentRequestDOList = paymentRequestManager.selectByQuery(paymentRequestQuery);
            if(!CollectionUtils.isEmpty(paymentRequestDOList)){
                PaymentRequestDO paymentRequestDO= paymentRequestDOList.get(0);
                log.info("已存在数据，开始更新垫款申请记录...");
                paymentRequestRecord.setPaymentRequestId(paymentRequestDO.getPaymentRequestId());
                paymentRequestManager.updateByPrimaryKeySelective(paymentRequestRecord);
                log.info("更新垫款申请记录完成...");
            }else {
                log.info("开始新增垫款申请记录...");
                paymentRequestManager.insertSelective(paymentRequestRecord);
                log.info("新增垫款申请记录完成...");
            }
            return true;
        }
        throw new SuzukiCommonException(ErrorCodeEnum.SELECT_FAILURE);
    }
}
